<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2025-02-16
  Time: 14:21
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ page import="java.util.*"%>
<%@ page import="java.net.URL" %>
<%@ page import="java.net.URLConnection" %>
<%@ page import="weaver.file.Prop" %>
<%@ page import="com.jsl.NCCloud21Service" %>
<%@ page import="com.jsl.utils.ResultMessageUtil" %>
<%@ page import="com.google.gson.Gson" %>
<%@ page import="java.lang.reflect.Type" %>
<%@ page import="com.jsl.utils.Encryption" %>
<%@ page import="java.net.URLEncoder" %>
<%@ page import="com.jsl.utils.SHA256Util" %>
<%@ page import="java.net.HttpURLConnection" %>
<%@ page import="java.nio.charset.Charset" %>
<%@ page import="java.io.*" %>
<%
    class TestProp {
        public TestProp() {
        }

        // app_secret
        private  String client_secret = null;
        // 公钥
        private  String pubKey = null;
        // app_id
        private  String client_id = null;
        // ncc用户名
        private  String username = null;
        private  String usercode = null;
        // ncc用户名密码
        private  String pwd = null;
        // ncc账套
        private  String busi_center = null;
        private  String dsname = null;
        // 获取token方式：client_credentials、password
        private  String grant_type =  "client_credentials";
        // 服务器ip：port
        private  String baseUrl = null;
        // 返回值压缩加密级别
        private  String secret_level = null;
        // 请求参数
        private  String requestBody = null;
        // openapi请求路径
        private  String apiUrl = null;

        // 访问api获取到的access_token
        public  String token = null;
        // 重复调用检查
        public  String repeat_check = null;
        // 接口调用业务标识
        public  String busi_id = null;

        /**
         * 初始化参数
         */
        private  void init() {
            client_secret = Prop.getPropValue("JslWorkflow", "nc21_client_secret");
            client_id = Prop.getPropValue("JslWorkflow", "nc21_client_id");
            pubKey = Prop.getPropValue("JslWorkflow", "nc21_pubKey");
            username = Prop.getPropValue("JslWorkflow", "nc21_username");
            pwd = Prop.getPropValue("JslWorkflow", "nc21_pwd");
            busi_center = Prop.getPropValue("JslWorkflow", "nc21_busi_center");
            baseUrl = Prop.getPropValue("JslWorkflow", "nc21_baseUrl");
            //requestBody = Prop.getPropValue("JslWorkflow", "nc21_requestBody");
            //apiUrl = Prop.getPropValue("JslWorkflow", "nc21_apiUrl");
            grant_type = Prop.getPropValue("JslWorkflow", "nc21_grant_type");
            secret_level = Prop.getPropValue("JslWorkflow", "nc21_secret_level");
            //repeat_check = Prop.getPropValue("JslWorkflow", "nc21_repeat_check");
            //busi_id = Prop.getPropValue("JslWorkflow", "nc21_busi_id");
        }


        public  String testToken() throws Exception {
            init();
            String token = getToken();
            // token转对象，获取api访问所用token和secret
            //ResultMessageUtil returnData = new Gson().fromJson(token, (Type) ResultMessageUtil.class);

            //Map<String, String> data = (Map<String, String>) returnData.getData();
            //String access_token = data.get("access_token");
            //String security_key = data.get("security_key");
            //String refresh_token = data.get("refresh_token");
            return token;
        }


        /**
         * 获取access_token
         *
         * @return
         * @throws Exception
         */
        private  String getToken() throws Exception {
            String token = null;
            if ("password".equals(grant_type)) {
                // 密码模式
                token = getTokenByPWD();
            } else if ("client_credentials".equals(grant_type)) {
                // 客户端模式
                token = getTokenByClient();
            }
            return token;
        }


        /**
         * 客户端模式获取token
         *
         * @return
         * @throws Exception
         */
        private   String getTokenByClient() throws Exception {
            Map<String, String> paramMap = new HashMap<String, String>();
            // 密码模式认证
            paramMap.put("grant_type", "client_credentials");
            // 第三方应用id
            paramMap.put("client_id", client_id);
            // 第三方应用secret 公钥加密
            String secret_entryption = Encryption.pubEncrypt(pubKey, client_secret);
            System.out.println("secret_entryption：：" + secret_entryption);
            paramMap.put("client_secret", URLEncoder.encode(secret_entryption, "utf-8"));
            // 账套编码
            paramMap.put("biz_center", busi_center);
            // // TODO 传递数据源和ncc登录用户
//		paramMap.put("dsname", dsname);
            paramMap.put("usercode", usercode);

            // 签名
            String sign = SHA256Util.getSHA256(client_id + client_secret + pubKey, pubKey);
            paramMap.put("signature", sign);
            System.out.println("##gettoken sign::" + sign);

            String url = baseUrl + "/nccloud/opm/accesstoken";
            String mediaType = "application/x-www-form-urlencoded";
            String token = doPost(url, paramMap, mediaType, null, "");
            return token;
        }

        /**
         * 密码模式获取token
         *
         * @return
         * @throws Exception
         */
        @SuppressWarnings("unused")
        private   String getTokenByPWD() throws Exception {
            Map<String, String> paramMap = new HashMap<String, String>();
            // 密码模式认证
            paramMap.put("grant_type", "password");
            // 第三方应用id
            paramMap.put("client_id", client_id);
            // 第三方应用secret 公钥加密
            paramMap.put("client_secret", URLEncoder.encode(Encryption.pubEncrypt(pubKey, client_secret), "utf-8"));
//		paramMap.put("client_secret", client_secret);
            // ncc用户名
            paramMap.put("username", username);
            // 密码 公钥加密
            paramMap.put("password", URLEncoder.encode(Encryption.pubEncrypt(pubKey, pwd), "utf-8"));
//		paramMap.put("password", pwd);
            // 账套编码
            paramMap.put("biz_center", busi_center);
            // 签名
            String sign = SHA256Util.getSHA256(client_id + client_secret + username + pwd + pubKey, pubKey);
            System.out.println("sign_getToken::" + sign);
            paramMap.put("signature", sign);

            String url = baseUrl + "/nccloud/opm/accesstoken";
            String mediaType = "application/x-www-form-urlencoded";
            String token = doPost(url, paramMap, mediaType, null, "");
            return token;
        }


        private  String doPost(String baseUrl, Map<String, String> paramMap, String mediaType, Map<String, String> headers, String json) {

            HttpURLConnection urlConnection = null;
            InputStream in = null;
            OutputStream out = null;
            BufferedReader bufferedReader = null;
            String result = null;
            try {
                StringBuffer sb = new StringBuffer();
                sb.append(baseUrl);
                if (paramMap != null) {
                    sb.append("?");
                    for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                        String key = entry.getKey();
                        String value = entry.getValue();
                        sb.append(key + "=" + value).append("&");
                    }
                    baseUrl = sb.toString().substring(0, sb.toString().length() - 1);
                }

                URL urlObj = new URL(baseUrl);
                urlConnection = (HttpURLConnection) urlObj.openConnection();
                urlConnection.setConnectTimeout(50000);
                urlConnection.setRequestMethod("POST");
                urlConnection.setDoOutput(true);
                urlConnection.setDoInput(true);
                urlConnection.setUseCaches(false);
                urlConnection.addRequestProperty("content-type", mediaType);
                if (headers != null) {
                    for (String key : headers.keySet()) {
                        urlConnection.addRequestProperty(key, headers.get(key));
                    }
                }
                out = urlConnection.getOutputStream();
                out.write(json.getBytes("utf-8"));
                out.flush();
                int resCode = urlConnection.getResponseCode();
                if (resCode == HttpURLConnection.HTTP_OK || resCode == HttpURLConnection.HTTP_CREATED || resCode == HttpURLConnection.HTTP_ACCEPTED) {
                    in = urlConnection.getInputStream();
                } else {
                    in = urlConnection.getErrorStream();
                }
                bufferedReader = new BufferedReader(new InputStreamReader(in, "utf-8"));
                StringBuffer temp = new StringBuffer();
                String line = bufferedReader.readLine();
                while (line != null) {
                    temp.append(line).append("\r\n");
                    line = bufferedReader.readLine();
                }
                String ecod = urlConnection.getContentEncoding();
                if (ecod == null) {
                    ecod = Charset.forName("utf-8").name();
                }
                result = new String(temp.toString().getBytes("utf-8"), ecod);
            } catch (Exception e) {
                System.out.println(e);
            } finally {
                if (null != bufferedReader) {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != out) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != in) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                urlConnection.disconnect();
            }
            return result;
        }
    }
%>

<%
    out.print("message : test");

    TestProp prop = new TestProp();

    try {
        out.print("message : "+prop.testToken());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }


%>

